package com.school.movie.common.component;

import com.school.movie.business.web.model.vo.UserVo;
import com.school.movie.dao.UserMapper;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author swift
 */
@Component
public class JurisdictionRealm extends AuthorizingRealm {

    /**
     * component和configuration极力推荐只注入dao类（因为这些类一般不用spring进行代理增强）
     * 如果在configuration中注入的是需要代理增强的类那模spring就会放弃对该类进行代理增强，那模你在这个
     * service的任何增强，比如事务管理都会无效，因为他注入的是你原来的类，不是增强之后的代理类
     */
    @Resource
    private UserMapper userMapper;


    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 用户认证
     *
     * @param token
     * @return
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
        UsernamePasswordToken userNamePasswordToken = (UsernamePasswordToken) token;
        String phoneNumber = userNamePasswordToken.getUsername();
        if (Objects.isNull(phoneNumber)) {
            return null;
        }

        UserVo user = userMapper.getById(phoneNumber);
        if (Objects.isNull(user)) {
            return null;
        }

        return new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
    }

    /**
     * 用户授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return new SimpleAuthorizationInfo();
    }

}